﻿using System;

using Microsoft.Practices.EnterpriseLibrary.Data.Instrumentation;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace Dynamic.Facades.EntLib.Data
{
    /// <summary>
    /// 数据库工厂类，通过配置（连接字符串）决定产生的具体实例
    /// </summary>
    public static class DatabaseFactory
    {
        /// <summary>
        /// 创建数据库实例（由默认连接字符串决定）
        /// </summary>
        /// <returns>数据库实例</returns>
        public static Database CreateDatabase()
        {
            Microsoft.Practices.EnterpriseLibrary.Data.Database db;
            try
            {
                db = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase();
                
                return new Database(db);
            }
            catch(Exception ex)
            {
                throw ex; 
            }   
        }

        /// <summary>
        /// 创建数据库实例（由指定连接字符串决定）
        /// </summary>
        /// <param name="name">连接字符串名称</param>
        /// <returns>数据库实例</returns>
        public static Database CreateDatabase(string name)
        {
            Microsoft.Practices.EnterpriseLibrary.Data.Database db;
            try
            {
                db = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase(name);

                return new Database(db);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="configurationException"></param>
        /// <param name="instanceName"></param>
        private static void TryLogConfigurationError(Exception configurationException, string instanceName)
        {
            try
            {
                DefaultDataEventLogger eventLogger = EnterpriseLibraryContainer.Current.GetInstance<DefaultDataEventLogger>();
                if (eventLogger != null)
                {
                    eventLogger.LogConfigurationError(configurationException, instanceName);
                }
            }
            catch { }
        }
    }
}
